<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="attr" v-for="(attr,index) in item.attr_vals" :key="index"></el-checkbox>

              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 静态属性 -->
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item) in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload :on-success="handleSuccess" :headers="headerObj"
              action="http://127.0.0.1:8888/api/private/v1/upload" list-type="picture-card"
              :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- 缩略图 -->
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-tab-pane>
          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce">
            </quill-editor>
            <!-- 按钮 -->
            <el-button type="primary" @click="add" style="margin-top:10px">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
  export default {
    name: "Add",
    data() {
      return {
        activeIndex: "0",
        //添加商品的表单数据对象
        addForm: {
          goods_name: "",
          goods_price: 0,
          goods_weight: 0,
          goods_number: 0,
          //级联选择器存储的数据
          goods_cat: [],
          //图片的数字
          pics: [],
          // 文本编辑器的数据
          goods_introduce: "",
          attrs: []
        },
        //分类数据列表
        cateList: [],
        //级联选择器需要的数据
        cateProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: "children"
        },
        //动态参数列表数据
        manyTableData: [],
        //静态属性参数列表
        onlyTableData: [],
        //添加图片需要的数据
        dialogImageUrl: '',
        dialogVisible: false,
        //图片请求头
        headerObj: {
          Authorization: localStorage.getItem("TOKEN")
        },

        //添加商品的表单验证
        addFormRules: {
          goods_name: [{
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }],
          goods_price: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }],
          goods_weight: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }],
          goods_number: [{
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }],
          goods_cat: [{
            required: true,
            message: '请选择商品分类',
            trigger: 'blur'
          }],
        }
      }
    },
    methods: {
      //获取分类数据
      async getCateList() {
        let result = await this.$requests.get("categories")
        if (result.meta.status == 200) {
          this.cateList = result.data
        } else {
          return this.$message.error("网络不佳,请稍后再试")
        }
      },
      //级联选择改变时发生的回调
      handleChange() {
        if (this.addForm.goods_cat.length !== 3) {
          this.addForm.goods_cat = []
        }
      },
      //tabs标签页切换时候触发
      beforeTabLeave(activeName, oldActiveName) {
        // console.log(activeName, oldActiveName)
        if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
          this.$message.error("请先选择商品分类")
          return false
        }
      },
      //tabs标签页切换时候触发
      async tabClicked() {
        // 动态参数面板
        if (this.activeIndex === "1") {
          let result = await this.$requests.get(`categories/${this.cataId}/attributes`, {
            params: {
              sel: "many"
            }
          })
          if (result.meta.status == 200) {
            result.data.forEach(item => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ")
            });
            this.manyTableData = result.data
          } else {
            return this.$message.error("网络不佳,请稍后再试")
          }
        }
        //静态属性面板
        if (this.activeIndex === "2") {
          let result = await this.$requests.get(`categories/${this.cataId}/attributes`, {
            params: {
              sel: "only"
            }
          })
          if (result.meta.status == 200) {
            this.onlyTableData = result.data
          } else {
            return this.$message.error("网络不佳,请稍后再试")
          }
        }
      },
      //移除图片的回调
      handleRemove(file, fileList) {
        //获取删除的图片信息
        const filePth = file.response.data.tmp_path
        //得到删除图片的索引值
        const i = this.addForm.pics.findIndex((item) => {
          return item.pic == filePth
        })
        //删除这一项
        this.addForm.pics.splice(i, 1)
      },
      // 图片预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      //图片上传成功的回调
      handleSuccess(response) {
        const picInfo = {
          pic: response.data.tmp_path
        }
        this.addForm.pics.push(picInfo)
      },
      //添加按钮的回调
      add() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            // 发送请求
            const form = JSON.parse(JSON.stringify(this.addForm))
            form.goods_cat = form.goods_cat.join(",")
            //处理动态参数和静态属性
            this.manyTableData.forEach((item) => {
              const newInfo = {
                attrId: item.attr_id,
                attr_value: item.attr_vals.join(" ")
              }
              this.addForm.attrs.push(newInfo)
            })
            this.onlyTableData.forEach((item) => {
              const newInfo = {
                attrId: item.attr_id,
                attr_value: item.attr_vals
              }
              this.addForm.attrs.push(newInfo)
            })
            form.attrs = this.addForm.attrs
            let result = await this.$requests.post("goods", form)

            if (result.meta.status == 201) {
              this.$message.success("添加成功")
              this.$router.push("/goods")
            } else {
              this.$message.error(result.meta.msg)
              return
            }
          } else {
            this.$message.error("请填写必要的表单项")
            return false;
          }
        });
      }
    },
    mounted() {
      this.getCateList()
    },
    computed: {
      cataId() {
        return this.addForm.goods_cat.length === 3 ? this.addForm.goods_cat[2] : null
      }
    }
  }

</script>

<style scoped lang="less">
  .el-checkbox {
    margin: 0 10px 0 0 !important;
  }

</style>
